package cn.study.zgm.nettyall.channel;

import io.netty.util.CharsetUtil;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;

/**
 * packageName cn.study.zgm.nettyall.channel
 *
 * @author 你的名字
 * @version JDK 8
 * @className ByteBufferTsString (此处以class为例)
 * @date 2025/2/24
 * @description TODO
 */
public class ByteBufferTsString {
    public static void main(String[] args) {

        // 1 字符串转为ByteBuffer(不会自动切换为读模式)
        ByteBuffer buffer1 = ByteBuffer.allocate(10);
        System.out.println("----------String.getBytes()-------------");
        buffer1.put("abcdef".getBytes());
        ByteBufferUtil.debugAll(buffer1);
        buffer1.get();
        ByteBufferUtil.debugAll(buffer1);



        // 2 Charsets转为buffer(会自动切换为读模式)
        System.out.println("----------StandardCharsets.UTF_8.decode-------------");
        ByteBuffer buffer2 = StandardCharsets.UTF_8.encode("abcdef");
        ByteBufferUtil.debugAll(buffer2);
        buffer2.get();
        ByteBufferUtil.debugAll(buffer2);

        // 3 wrap(会自动切换为读模式)
        System.out.println("----------ByteBuffer.wrap-------------");
        ByteBuffer buffer3 = ByteBuffer.wrap("abcdefg".getBytes());
        ByteBufferUtil.debugAll(buffer3);
        buffer3.get();
        ByteBufferUtil.debugAll(buffer3);

        System.out.println("----------测试读取-------------");
        ByteBuffer buffer4 = StandardCharsets.UTF_8.encode("abcdef");
        String str4 = StandardCharsets.UTF_8.decode(buffer4).toString();
        System.out.println("打印buffer4"+str4);


        //
        ByteBuffer buffer5 = ByteBuffer.allocate(10);
        buffer5.put("abcdef".getBytes());
        // 读取不到数据，必须手动切换
        buffer5.flip();
        String str5 = StandardCharsets.UTF_8.decode(buffer5).toString();
        System.out.println("打印buffer5"+str5);
    }
}
